package com.github.xzb617.client.flow.core.statics;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 统计器
 * <p>
 *     统计的数据汇总、获取
 * </p>
 * @author xzb617
 */
public class Statics {

    private final static Window timeWindowInSecond;
    private final static Window timeWindowInMinute;
    private static Long lastGetMetricTime;

    static {
        timeWindowInSecond = new Window(1000, 500);
        timeWindowInMinute = new Window(60000, 1000);
    }

    public static void addTotal(long currentTimestamp) {
        Slice sliceInSecond = timeWindowInSecond.getCurrentSlice(currentTimestamp);
        Slice sliceInMinute = timeWindowInMinute.getCurrentSlice(currentTimestamp);
        sliceInSecond.addTotalCount(1);
        sliceInMinute.addTotalCount(1);
    }

    public static void addPass(long currentTimestamp) {
        Slice sliceInSecond = timeWindowInSecond.getCurrentSlice(currentTimestamp);
        Slice sliceInMinute = timeWindowInMinute.getCurrentSlice(currentTimestamp);
        sliceInSecond.addPassCount(1);
        sliceInMinute.addPassCount(1);
    }

    public static long getCurrentQPS(long currentTimestamp) {
        return timeWindowInSecond.getQPS(currentTimestamp);
    }

    public static long getTotalCount(long currentTimestamp) {
        return timeWindowInSecond.getTotalCount(currentTimestamp);
    }

    public static long getPassCount(long currentTimestamp) {
        return timeWindowInSecond.getPassCount(currentTimestamp);
    }

    /**
     * 收集当前时间所在分钟的指标数据
     * @return
     */
    public static Map<String, String> collectMetricsInMinute() {
        long currentTimestamp = System.currentTimeMillis();
        long startTime = currentTimestamp - (currentTimestamp % 1000);
        long totalCount = timeWindowInMinute.getTotalCount(currentTimestamp);
        long passCount = timeWindowInMinute.getPassCount(currentTimestamp);
        long failCount = totalCount - passCount;
        Map<String, String> flowMetric = new HashMap<>(8);
        flowMetric.put("startTime", String.valueOf(startTime));
        flowMetric.put("totalCount", String.valueOf(totalCount));
        flowMetric.put("passCount", String.valueOf(passCount));
        flowMetric.put("failCount", String.valueOf(failCount));
        return flowMetric;
    }

}
